package com.online.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.online.shopping.activemq.JmsConfig;
import com.online.shopping.pojo.*;
import com.online.shopping.service.GoodService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.web.bind.annotation.*;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.Topic;
import java.util.List;

/**
 * @author Rui
 * @version 1.0
 * @date 2020/11/23 16:43
 */
@RestController
@CrossOrigin
@Slf4j
@RequestMapping("/manager/good")
@Api(tags = "商品管理", description = "商品增删改查")
public class GoodsController {

    @Autowired
    private GoodService goodService;

    /**
     * 返回全部列表
     * @return
     */
    @ApiOperation("查找全部商品")
    @RequestMapping("/findAll")
    public List<TbGoods> findAll(){
        return goodService.findAll();
    }

    /**
     * 返回全部列表
     * @return
     */
    @ApiOperation("分页")
    @RequestMapping("/findPage")
    public ResultPage findPage(int page,int rows){
        return goodService.findPage(page, rows);
    }

    /**
     * 增加
     * @param goods
     * @return
     */
    @ApiOperation("添加商品")
    @RequestMapping("/add")
    public CommonResult add(@RequestBody Goods goods){
        System.out.println("#######"+goods.getGoods().getGoodsName()+"#######");
        System.out.println("#######"+goods.getGoodsDesc().getItemImages());
        System.out.println("#######"+goods.getGoodsDesc().getSpecificationItems());
        System.out.println("#######"+goods.getGoodsDesc().getCustomAttributeItems());

        try {
            // 获得商家信息:
            //String sellerId = SecurityContextHolder.getContext().getAuthentication().getName();
            String sellerId = "yqtech"; //暂时设定
            goods.getGoods().setSellerId(sellerId);

            goodService.add(goods);
            return new CommonResult(200, "增加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "增加失败");
        }
    }

    /**
     * 修改
     * @param goods
     * @return
     */
    @ApiOperation("修改商品")
    @RequestMapping("/update")
    public CommonResult update(@RequestBody Goods goods){
        // 获得商家信息:
        //String sellerId = SecurityContextHolder.getContext().getAuthentication().getName();
        String sellerId = "yqtech"; //暂时设定
        Goods goods2 = goodService.findOne(goods.getGoods().getId());
        if(!sellerId.equals(goods2.getGoods().getSellerId()) || !sellerId.equals(goods.getGoods().getSellerId())){
            return new CommonResult(400, "非法操作");
        }
        try {
            goodService.update(goods);
            return new CommonResult(200, "修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "修改失败");
        }
    }

    /**
     * 获取实体
     * @param id
     * @return
     */
    @ApiOperation("根据id查找商品")
    @RequestMapping("/findOne")
    public Goods findOne(Long id){
        return goodService.findOne(id);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @ApiOperation("删除商品")
    @RequestMapping("/delete")
    public CommonResult delete(Long [] ids){
        try {
            goodService.delete(ids);
            return new CommonResult(200, "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "删除失败");
        }
    }

    /**
     * 查询+分页
     * @param page
     * @param rows
     * @return
     */
    @ApiOperation("查询商品")
    @RequestMapping("/search")
    public ResultPage search(@RequestBody TbGoods goods, int page, int rows  ){

        //查询
//        String sellerId = SecurityContextHolder.getContext().getAuthentication().getName();
        String sellerId = "yqtech"; //暂时设定
        goods.setSellerId(sellerId);

        return goodService.findPage(goods, page, rows);
    }

    @Autowired
    private JmsTemplate jmsTemplate;

    @ApiOperation("更新商品状态")
    @RequestMapping("/updateStatus")
    public CommonResult updateStatus(Long[] ids,String status){
        System.out.println("ids: " + ids);
        System.out.println("status: " + status);
        try {
            goodService.updateStatus(ids, status);  //1. 更改数据库中tb_goods表中audit_status 0-->1

            if("1".equals(status)){//如果是审核通过
                //*****导入到索引库
                //得到需要导入的SKU列表    根据spu的id查询对应的sku的商品
                List<TbItem> itemList = goodService.findItemListByGoodsIdListAndStatus(ids, status);
                //2. 导入到solr
//                itemSearchService.importList(itemList);
                final String jsonString = JSON.toJSONString(itemList);//转换为json传输

                System.out.println("Goods controller: " + jsonString);

                Topic topicSolrDestination = new ActiveMQTopic(JmsConfig.TOPIC_SOLR);
                jmsTemplate.send(topicSolrDestination, new MessageCreator() {

                    @Override
                    public Message createMessage(Session session) throws JMSException {

                        return session.createTextMessage(jsonString);
                    }
                });

                //****3. 生成商品详细页 freemarker
                for(final Long goodsId:ids){
                    Topic topicPageDestination = new ActiveMQTopic(JmsConfig.TOPIC_HTML);
                    jmsTemplate.send(topicPageDestination, new MessageCreator() {

                        @Override
                        public Message createMessage(Session session) throws JMSException {
                            return session.createTextMessage(goodsId+"");
                        }
                    });
                }
            }
            return new CommonResult(200, "修改状态成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult(400, "修改状态失败");
        }
    }

}
